package cn.lcvc.xnc.application.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.lcvc.xnc.application.common.exception.model.MyWebException;
import cn.lcvc.xnc.application.common.model.result.ResponseData;
import cn.lcvc.xnc.application.common.utils.file.MyFileUpload;
import cn.lcvc.xnc.application.common.utils.requests.RequestUtil;
import cn.lcvc.xnc.application.dao.WasteDisposalMappingMapper;
import cn.lcvc.xnc.application.dao.WasteDisposalMappingPictureMapper;
import cn.lcvc.xnc.application.model.WasteDisposalMappingPicture;
import cn.lcvc.xnc.application.model.query.WasteDisposalMappingPictureQuery;
import cn.lcvc.xnc.application.service.WasteDisposalMappingPictureService;
import cn.lcvc.xnc.authority.config.upload.FileUploadConfig;
import cn.lcvc.xnc.authority.model.SysUser;
import cn.lcvc.xnc.authority.service.impl.IBaseService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;


/**
 * @description 专业群的业务层接口
 * @author 王秋林
 * @date 2022-7-18 16:00
 */
@Service
@Slf4j
public class IWasteDisposalMappingPictureService extends IBaseService<WasteDisposalMappingPicture, WasteDisposalMappingPictureQuery> implements WasteDisposalMappingPictureService {

    @Autowired
    private WasteDisposalMappingPictureMapper mapper;

    @Autowired
    private WasteDisposalMappingMapper wasteDisposalMappingMapper;

    @Autowired
    private FileUploadConfig fileUploadConfig;
    @Override
    protected void beforeGet(Serializable id) {
        if(mapper.findById(id)==null){
            throw new MyWebException("查找失败：找不到指定记录");
        }
    }

    @Override
    protected void beforeUpdate(WasteDisposalMappingPicture wasteDisposalMappingPicture) throws MyWebException {
        if(wasteDisposalMappingPicture.getId()==null){
            throw new MyWebException("编辑失败：id不能为空");
        }
        if(mapper.findById(wasteDisposalMappingPicture.getId())==null){
            throw new MyWebException("编辑失败：找不到指定记录");
        }
//        /**
//         * 重新处理专业群和群主的关系。
//         * 考虑到关系表没有自增id，且专业群和群主关系的数量不会多，本来可以简化逻辑：先全部删除该专业群所有群主关系，再重新添加
//         * 但为了保证专业群和群主关系的建立时间可查，故采用规范的判断
//         */
//        //将前端传递过来的集合转换为set集合,顺便去重
//        Set<Integer> teacherIdsSet = new HashSet<Integer>(Arrays.asList(wasteDisposalMapping.getTeacherIds()));
//        //获取所有的群主
//        List<SchoolTeacher> teachersOfAll=schoolTeacherMapper.findAll(null);
//        //获取原来的群主
//        List<SchoolTeacher> teachersOrigin=schoolMajorGroupTeacherMapper.findAllTeacherByMajorGroupId(schoolMajorGroup.getId());
//        //处理专业群和群主的关系
//        for(SchoolTeacher schoolTeacher:teachersOfAll){
//            if(teacherIdsSet.contains(schoolTeacher.getId())){//如果前端勾选了该群主
//                if(!teachersOrigin.contains(schoolTeacher)){//如果该群主原来不存在
//                    //添加该群主关系
//                    schoolMajorGroupTeacherMapper.save(schoolMajorGroup.getId(),schoolTeacher.getId(),schoolMajorGroup.getType());
//                }
//            }else{//如果没有勾选该群主
//                if(teachersOrigin.contains(schoolTeacher)) {//如果该群主原来存在
//                    //移除该群主关系
//                    schoolMajorGroupTeacherMapper.delete(schoolMajorGroup.getId(),schoolTeacher.getId());
//                }
//            }
//        }

    }

    @Override
    protected void beforeSave(WasteDisposalMappingPicture wasteDisposalMappingPicture) {
//        if (wasteDisposalMapping.getDepartmentId() != null){//如果专业群对应部门不为空
//            SysDepartment sysDepartment = schoolDepartmentMapper.findBySysDepartmentId(schoolMajorGroup.getDepartmentId());
//                if (sysDepartment.getParentId() != null){
//                    //如果专业群对应部门不是学校而是系部则添加
//                    //赋值
//                    schoolMajorGroup.setDepartmentId(schoolDepartmentMapper.findIdByParentIdAndName(Math.toIntExact(sysDepartment.getParentId()),sysDepartment.getName()));
//                }else {
//                    throw new MyWebException("添加失败：该专业群部门不能为学校");
//                }
//        }else{
//            throw new MyWebException("添加失败：找不到指定记录");
//        }
//        //判断专业群是否存在
//        if(mapper.countByName(schoolMajorGroup.getName())>0){
//            throw new MyWebException("添加失败：该专业群已存在");
//        }
    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
//        schoolMajorGroupTeacherMapper.deleteByMajorGroupIds(ids);
    }


    @Override
    protected void afterGet(WasteDisposalMappingPicture wasteDisposalMappingPicture) {
//            //添加部门关联属性
//            if (schoolMajorGroup.getDepartmentId() != null) {
//                //查找专业所属部门
//                SchoolDepartment schoolDepartment = schoolDepartmentMapper.findById(schoolMajorGroup.getDepartmentId());
//                //赋值
//                schoolMajorGroup.setSchoolDepartment(schoolDepartment);
//            }
    }

    @Override
    protected void afterFindAll(List<WasteDisposalMappingPicture> list) {
//        for (SchoolMajorGroup schoolMajorGroup : list) {
//            //添加部门关联属性
//            if (schoolMajorGroup.getDepartmentId() != null) {
//                //查找专业所属部门
//                SchoolDepartment schoolDepartment = schoolDepartmentMapper.findById(schoolMajorGroup.getDepartmentId());
//                //赋值
//                schoolMajorGroup.setSchoolDepartment(schoolDepartment);
//            }
//            //添加部门下群主数量值
//            schoolMajorGroup.setTeacherNumber(schoolMajorGroupTeacherMapper.countAllTeacherByMajorGroupId(schoolMajorGroup.getId()));
//        }
    }

    @Override
    protected void afterSave(WasteDisposalMappingPicture wasteDisposalMappingPicture) {
//        if (schoolMajorGroup.getTeacherIds() != null && schoolMajorGroup.getType()!= null){
//            for(Integer teacherId:schoolMajorGroup.getTeacherIds()){
//                schoolMajorGroupTeacherMapper.save(schoolMajorGroup.getId(),teacherId,schoolMajorGroup.getType());
//            }
//        }
    }
    public List<String> uploadImgFile(Integer id, MultipartFile[] file) {
        List<String> urlList =  new ArrayList<>();
        for (MultipartFile files : file) {
            if (files.isEmpty()) {
                throw new MyWebException("请选择要上传的图片");
            } else {
                //图片保存位置
                String filePath = "C:\\img\\";
                //创建文件mulu
                FileUtil.mkdir(filePath);
                //获取文件名
                String fileName = files.getOriginalFilename();
                //获取文件扩展名
                String extensionName = FileUtil.extName(fileName);
//                修改文件名为时间戳
                fileName = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + "." + extensionName;
                //获取文件类型
                String fileType = files.getContentType();
                if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpg")) {
                    if (files.getSize() / 1000 > 10000) {
                        throw new MyWebException("图片大小不能超过10M,请重新选择要上传的图片");
                    }
                    try {
                        WasteDisposalMappingPicture pic = new WasteDisposalMappingPicture();
                        pic.setMappingId(id);
                        pic.setPictureUrl(fileName);
                        urlList.add(fileName);
                        files.transferTo(new File(filePath + fileName));
                    } catch (IOException e) {
                        throw new MyWebException("上传失败：" + e.getMessage());
                    }
                } else {
                    throw new MyWebException("图片格式错误");
                }
            }
        }
        return urlList;
    }

}
